import time
from playwright.sync_api import sync_playwright
import os
import json

# --- 配置 ---
AUTH_FILE = "auth_state.json"
COOKIE_FILE = "cookies.txt"  # 保存原始Cookie字符串的文件
DOUBAN_LOGIN_URL = "https://accounts.douban.com/passport/login?source=group"

def read_json_file(filename):
    """读取JSON文件并返回Python对象"""
    try:
        with open(filename, 'r', encoding='utf-8') as file:
            return json.load(file)
    except Exception as e:
        print(f"错误: 读取文件时发生异常 - {e}")
        return None

def cookies_to_string(cookies_list):
    """将cookies列表转换为原始字符串格式"""
    cookie_parts = []
    for cookie in cookies_list:
        name = cookie.get('name', '')
        value = cookie.get('value', '')
        if name and value:
            cookie_parts.append(f"{name}={value}")
    return '; '.join(cookie_parts)

def run():
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        context = browser.new_context()
        page = context.new_page()

        print("正在打开豆瓣登录页...")
        page.goto(DOUBAN_LOGIN_URL)

        print("-" * 50)
        print("请在弹出的浏览器窗口中手动完成登录")
        print("登录成功后，脚本会自动保存状态")
        print("浏览器将保持打开状态供您使用")
        print("-" * 50)

        try:
            page.wait_for_url("https://www.douban.com/", timeout=0)
            print("\n✅ 检测到登录成功！")
            time.sleep(2)
            
            # 保存状态
            context.storage_state(path=AUTH_FILE)
            
            # 处理cookies
            json_data = read_json_file(AUTH_FILE)
            if json_data:
                cookies = json_data.get("cookies", [])
                
                # 生成原始字符串格式
                cookie_string = cookies_to_string(cookies)
                
                # 直接保存原始字符串到 cookie.txt
                with open(COOKIE_FILE, 'w', encoding='utf-8') as file:
                    file.write(cookie_string)
                
                print(f"✅ 登录状态已保存到: {os.path.abspath(AUTH_FILE)}")
                print(f"✅ Cookie原始字符串已保存到: {os.path.abspath(COOKIE_FILE)}")
                
                # 打印Cookie字符串
                print("\n" + "="*50)
                print("Cookie原始字符串:")
                print("="*50)
                print(cookie_string)
                print("="*50)
            
        except Exception as e:
            print(f"等待登录时发生错误: {e}")

        print("-" * 50)
        print("脚本执行完成，浏览器保持打开状态")
        print("您可以继续在浏览器中操作")
        print("如需关闭，请手动关闭浏览器窗口")
        print("-" * 50)
        
        # 无限循环，保持脚本运行，浏览器不关闭
        while True:
            try:
                time.sleep(10)  # 每10秒检查一次
            except KeyboardInterrupt:
                print("\n用户中断脚本")
                break

if __name__ == "__main__":
    run()
